//
//  LoginViewController.m
//  LifeBox
//
//  Created by admin on 2019/8/13.
//  Copyright © 2019 Lucky. All rights reserved.
//

#import "LoginViewController.h"
#import "Userinfo.h"
#import "LoginCodeView.h"
#import "LoginPwView.h"
#import "RegisterController.h"
#import "Network+Login.h"

@interface LoginViewController ()<UITextFieldDelegate> {
    ///设定倒计时Key
    NSString *keyStr;
}

///验证码登录View
@property (strong, nonatomic) LoginCodeView *codeView;
///密码登录View
@property (strong, nonatomic) LoginPwView *pwView;
///登录按钮
@property (strong, nonatomic) UIButton *loginBtn;
///选择按钮
@property (strong, nonatomic) UIButton *chooseBtn;
///关闭按钮
@property (strong, nonatomic) UIButton *clostBtn;
///协议Label
@property (strong, nonatomic) UILabel *describeLaebl;
////  注册按钮
@property (strong, nonatomic) UIButton *registerBtn;
//// 标题
@property (strong, nonatomic) UILabel *titlLab;
////  登陆方式 0密码登陆 1验证码登陆
@property (assign, nonatomic) NSInteger loginType;


@end

@implementation LoginViewController

#pragma mark - 视图层
- (void)viewDidLoad {
    [super viewDidLoad];
    [self createUI];
    self.loginType = 0;
    /*
     * 初始化数据
     */
    keyStr = @"LoginViewControllerKey";
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"LoginUserInfo"];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationDoit) name:APPTIMEINFORMATION object:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = NO;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self.view endEditing:YES];
}

#pragma mark - 创建UI
-(void)createUI {

    [self.view addSubview:self.clostBtn];
    [self.view addSubview:self.titlLab];
    [self.view addSubview:self.codeView];
    [self.view addSubview:self.pwView];
    [self.view addSubview:self.loginBtn];
    [self.view addSubview:self.chooseBtn];
    [self.view addSubview:self.registerBtn];

    UG_WEAKSELF
    [self bk_addObserverForKeyPaths:@[@"loginType",
                                      @"codeView.phoneTF.text",
                                      @"codeView.codeTF.text",
                                      @"pwView.passwTF.text",
                                      @"pwView.phoneTF.text"
    ] task:^(id obj, NSString *keyPath) {
        
        if(weakSelf.loginType == 0){
            weakSelf.codeView.hidden = YES;
            weakSelf.pwView.hidden = NO;
            [weakSelf.chooseBtn setTitle:@"验证码登录" forState:UIControlStateNormal];
            [weakSelf.titlLab setText:@"账号/手机号密码登录"];
            if (weakSelf.pwView.passwTF.text.length <= KPASSWORDLENGTH && weakSelf.pwView.passwTF.text.length >= KPASSWORDMINLENGTH && weakSelf.pwView.phoneTF.text.length == 11) {
        
                weakSelf.loginBtn.enabled = YES;
                weakSelf.loginBtn.alpha = 1;
            }else{
               weakSelf.loginBtn.alpha = 0.6;
                weakSelf.loginBtn.enabled = NO;
            }
            
        }
        if(weakSelf.loginType == 1){
            weakSelf.codeView.hidden = NO;
            weakSelf.pwView.hidden = YES;
            [weakSelf.titlLab setText:@"验证码登录"];
            [weakSelf.chooseBtn setTitle:@"账号/手机号密码登录" forState:UIControlStateNormal];
            if (weakSelf.codeView.codeTF.text.length == 6 && weakSelf.codeView.phoneTF.text.length == 11) {
                weakSelf.loginBtn.alpha = 1;
                weakSelf.loginBtn.enabled = YES;
            }else{
                weakSelf.loginBtn.alpha = 0.6;
                weakSelf.loginBtn.enabled = NO;
                
            }
        }
        
    }];
    
    /*
     * 协议Lable
     */
//    _describeLaebl = [[WPHotspotLabel alloc] init];
//    _describeLaebl.textAlignment = NSTextAlignmentCenter;
//    _describeLaebl.backgroundColor = [UIColor clearColor];
//    _describeLaebl.font = [UIFont systemFontOfSize:KAutoAcale(12)];
//    _describeLaebl.textColor = COLORDANGER;
//    _describeLaebl.numberOfLines = 0;
//    _describeLaebl.userInteractionEnabled = YES;
//    [self.view addSubview:_describeLaebl];
//    /*提示文字点击部分*/
//    NSMutableDictionary *mudic = [[NSMutableDictionary alloc]initWithCapacity:0];
//    [mudic setValue:[UIFont fontWithName:@"HelveticaNeue" size:KAutoAcale(12)] forKey:@"body"];
//    NSMutableString *textStr = [NSMutableString stringWithString:@"点击登录，即代表您已同意"];
//    NSInteger i = 0;
//    NSString* keystr = [NSString stringWithFormat:@"help%d",(int)i];
//    [mudic setObject:[WPAttributedStyleAction styledActionWithAction:^{
//        /*
//         * 跳转协议
//         */
//        [self.view ug_msg:@"协议跳转"];
//    }] forKey:keystr];
//    NSString *nameStr = @"《用户协议》";
//    NSString *temstr = [NSString stringWithFormat:@"<%@>%@</%@>",keystr,nameStr,keystr];
//    [textStr appendString:temstr];
//    NSString* keystr1 = [NSString stringWithFormat:@"help1"];
//    [mudic setObject:[WPAttributedStyleAction styledActionWithAction:^{
//        /*
//         * 跳转协议
//         */
//        [self.view ug_msg:@"隐私保护协议跳转"];
//    }] forKey:keystr1];
//    NSString *nameStr1 = @"《隐私保护协议》";
//    NSString *temstr1 = [NSString stringWithFormat:@"和<%@>%@</%@>",keystr1,nameStr1,keystr1];
//    [textStr appendString:temstr1];
//    [mudic setValue:@[S_COGreenText] forKey:@"link"];//@{NSUnderlineStyleAttributeName : @(NSUnderlineStyleSingle|NSUnderlinePatternSolid)},
//    textStr = [NSMutableString stringWithString:[textStr substringToIndex:[textStr length]]];
//    _describeLaebl.attributedText = [textStr attributedStringWithStyleBook:mudic];
//    [_describeLaebl mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.bottom.mas_equalTo(-KAutoAcale(20));
//        make.left.mas_equalTo(KAutoAcale(20));
//        make.right.mas_equalTo(-KAutoAcale(20));
//        make.height.mas_equalTo(KAutoAcale(40));
//    }];
}

#pragma mark - 登录方式选择按钮点击
- (void)chooseBtnClick:(UIButton *)btn {
    [self.view endEditing:YES];
    if (btn.selected == NO) {
        self.loginType = 1;
    }else{
        self.loginType = 0;
    }
    btn.selected = !btn.selected;
}

#pragma mark - 登录Btn点击
- (void)loginBtnClicked:(UIButton *)btn {
    if (_loginType == 1) {
        //验证码登录
        [self loginWithCodeHttp];
    }else if (_loginType == 0){
        //密码登录
        [self loginWithPasswdHttp];
    }
}

#pragma mark - 获取验证码Btn点击
- (void)codeBtnClicked {
    [self.view endEditing:YES];
    if (self.codeView.phoneTF.text.length == 0) {
        return;
    }else{
        if (self.codeView.phoneTF.text.length < 11) {
            [self.view ug_msg:@"手机号码有误"];
            return;
        }
    }
    [self getCodeHttpWithPhone:self.codeView.phoneTF.text];
}

#pragma mark - 密码登录接口
- (void)loginWithPasswdHttp {
    [self.view ug_starloading];
    
    [[Network share] passlogin:_pwView.phoneTF.text passwd:[_pwView.passwTF.text encryptionSha1] block:^(NSDictionary * _Nullable result, NSError * _Nullable error) {
        [self.view ug_stoploading];
        if (error) {
            [self.view ug_msg:error.domain];
        }else{
            [UserInfo share].token = [result stringValueForKey:@"token" default:NULL];
            [[UserInfo share] modelSetWithJSON:[result objectForKey:@"userinfo"]];
            [self.navigationController dismissViewControllerAnimated:YES completion:nil];
        }
    }];
}

#pragma mark - 验证码登录接口
- (void)loginWithCodeHttp {
    [self.view ug_starloading];
    [[Network share] loginWihtCode:_codeView.codeTF.text phone:_codeView.phoneTF.text endBlock:^(NSDictionary * _Nullable result, NSError * _Nullable error) {
        [self.view ug_stoploading];
        if (error) {
            [self.view ug_msg:error.domain];
        }else{
            [UserInfo share].token = [result stringValueForKey:@"token" default:NULL];
            [[UserInfo share] modelSetWithJSON:[result objectForKey:@"userinfo"]];
            [[UserInfo share] save];
            [self.navigationController dismissViewControllerAnimated:YES completion:nil];
        }
    }];
}

#pragma mark - 请求验证码接口
- (void)getCodeHttpWithPhone:(NSString *)phone {
    [self.view ug_starloading];
    [[Network share] getAuthCode:phone block:^(NSDictionary * _Nullable dataDict, NSError * _Nullable error) {
        [self.view ug_stoploading];
        if (error) {
            [self.view ug_msg:error.domain];
        }else{
#ifdef DEBUG
            _codeView.codeTF.text = dataDict;
            _loginBtn.userInteractionEnabled = YES;
#endif
//            [AppDelegate addObjectIndateDic:self->keyStr];
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationDoit) name:APPTIMEINFORMATION object:nil];
        }
    }];
}

#pragma mark - 验证码监听
- (void)notificationDoit {
//    NSInteger codeNum = [AppDelegate getimeIntervalBy:keyStr wirhMax:30];
//    if (codeNum > 0) {
//        _codeView.codeBtn.userInteractionEnabled = NO;
//        [_codeView.codeBtn setTitle:[NSString stringWithFormat:@"重新获取(%ld)", (long)codeNum] forState:UIControlStateNormal];
//    }else{
//        _codeView.codeBtn.userInteractionEnabled = YES;
        [_codeView.codeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
//        [AppDelegate removeObjectKey:keyStr];
//    }
}

#pragma mark - get
-(UIButton *)clostBtn{
    if (!_clostBtn) {
        _clostBtn = [UIButton new];
        [_clostBtn setBackgroundImage:[UIImage imageWithIcon:@"fa-times" backgroundColor:UIColor.clearColor iconColor:COLORINFO andSize:CGSizeMake(KAutoAcale(32), KAutoAcale(32))] forState:UIControlStateNormal];
        [_clostBtn bk_addEventHandler:^(id sender) {
            [self.navigationController dismissViewControllerAnimated:YES completion:nil];
        } forControlEvents:UIControlEventTouchUpInside];
    }
    return _clostBtn;
}

-(UILabel *)titlLab{
    if (!_titlLab) {
        _titlLab = [UILabel new];
        _titlLab.font = [UIFont systemFontOfSize:KAutoAcale(30)];
        _titlLab.textColor = COLOR_23;
        _titlLab.text = @"账号/手机号密码登陆";
    }
    return _titlLab;
}

-(LoginCodeView *)codeView{
    if (!_codeView) {
        _codeView = [LoginCodeView new];
        _codeView.hidden = YES;
    }
    return _codeView;
  
}

-(LoginPwView *)pwView{
    if (!_pwView) {
        _pwView = [LoginPwView new];
    }
    return _pwView;
}


-(UIButton *)loginBtn{
    if (!_loginBtn) {
        _loginBtn = [UIButton new];
        
        _loginBtn.layer.cornerRadius = KAutoAcale(22);
        _loginBtn.backgroundColor = COLORDANGER;
        [_loginBtn setTitle:@"登录" forState:UIControlStateNormal];
        [_loginBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
        [_loginBtn addTarget:self action:@selector(loginBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _loginBtn;
}

-(UIButton *)registerBtn{
    if (!_registerBtn) {
        _registerBtn = [UIButton new];
        _registerBtn.titleLabel.font = [UIFont systemFontOfSize:KAutoAcale(12)];
        [_registerBtn setTitleColor:COLORDANGER forState:UIControlStateNormal];
        [_registerBtn setTitle:@"注册" forState:UIControlStateNormal];
        [_registerBtn bk_addEventHandler:^(id sender) {
            RegisterController *ctl = [[RegisterController alloc] init];
            [self.navigationController pushViewController:ctl animated:YES];
        } forControlEvents:UIControlEventTouchUpInside];
    }
    return _registerBtn;
}

-(UIButton *)chooseBtn{
    if (!_chooseBtn) {
        _chooseBtn = [UIButton new];
        _chooseBtn.titleLabel.font = [UIFont systemFontOfSize:KAutoAcale(12)];
            [_chooseBtn setTitleColor:COLORDANGER forState:UIControlStateNormal];
            [_chooseBtn setTitle:@"验证码登录" forState:UIControlStateNormal];
            _chooseBtn.selected = NO;
            [_chooseBtn addTarget:self action:@selector(chooseBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _chooseBtn;
}


-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    [_loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
         make.top.mas_equalTo(self.titlLab.mas_bottom).mas_offset(KAutoAcale(220));
         make.left.mas_equalTo(KAutoAcale(30));
         make.right.mas_equalTo(-KAutoAcale(30));
         make.height.mas_equalTo(KAutoAcale(45));
     }];
    [self.clostBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(KAutoAcale(25));
        make.top.mas_equalTo(KSAFE_Top+ KAutoAcale(10));
        make.width.height.mas_equalTo(KAutoAcale(20));
    }];
    [self.titlLab mas_makeConstraints:^(MASConstraintMaker *make) {
         make.left.mas_equalTo(KAutoAcale(30));
         make.top.mas_equalTo(self.clostBtn.mas_bottom).mas_offset(KAutoAcale(65));
         make.width.height.mas_greaterThanOrEqualTo(10);
     }];
    
    [_codeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.titlLab.mas_bottom).mas_offset(KAutoAcale(50));
        make.left.mas_equalTo(KAutoAcale(30));
        make.right.mas_equalTo(-KAutoAcale(30));
        make.height.mas_equalTo(KAutoAcale(125));
    }];
    [_pwView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.titlLab.mas_bottom).mas_offset(KAutoAcale(50));
        make.left.mas_equalTo(KAutoAcale(30));
        make.right.mas_equalTo(-KAutoAcale(30));
        make.height.mas_equalTo(KAutoAcale(125));
    }];
    [_chooseBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_loginBtn.mas_bottom).mas_offset(KAutoAcale(10));
        make.right.mas_equalTo(_loginBtn.mas_right);
        make.width.mas_greaterThanOrEqualTo(10);
        make.height.mas_equalTo(KAutoAcale(30));
    }];
    [_registerBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_loginBtn.mas_bottom).mas_offset(KAutoAcale(10));
        make.left.mas_equalTo(_loginBtn.mas_left);
        make.width.mas_equalTo(KAutoAcale(40));
        make.height.mas_equalTo(KAutoAcale(30));
    }];
}
@end
